﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TimScripts.BF4Rcon.Resources;

namespace TimScripts.BF4Rcon
{
    public class MapDataMapCollection : IMapCollection
    {
        private IList<string> Data;
        private int DataOffset;
        private const short InitialNumWords = 2;

        private int WordsPerMap { get { return Data[DataOffset + 1].ToInt(); } }

        public IMap this[int index]
        {
            get
            {
                if (index >= Count || index < 0)
                    throw new ArgumentOutOfRangeException("index", ErrorStrings.ArgumentOutOfRange_MapsInCollection);

                Map result = ParseMap(index);

                return result;
            }
        }

        public int Count
        {
            get
            {
                int result = Data[DataOffset].ToInt();

                return result;
            }
        }

        public MapDataMapCollection(IList<string> data, int offset)
        {
            if (data == null)
                throw new ArgumentNullException("data");

            Data = data;

            DataOffset = offset;
        }

        private Map ParseMap(int mapNum)
        {
            int offset = DataOffset + InitialNumWords + WordsPerMap * mapNum;
            string mapName;
            string gameMode;
            int numRounds;
            Map result;

            mapName = Data[offset++];
            gameMode = Data[offset++];
            numRounds = Data[offset++].ToInt();

            result = Map.Parse(mapName, gameMode, numRounds);

            return result;
        }

        public MapDataMapCollection(IList<string> data)
            : this(data, 0)
        {

        }

        public IEnumerator<IMap> GetEnumerator()
        {
            Map map;

            for (int i = 0; i < Count; i++)
            {
                map = ParseMap(i);

                yield return map;
            }
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }
}
